/**
 * @author Caius
 * @description
 *      控制层的实现类
 * @version 1.0
 * @since Created in 2024-12-09
 */

package com.itsense.lib_sys.controller;

import com.itsense.lib_sys.model.Book;
import com.itsense.lib_sys.response.Code;
import com.itsense.lib_sys.response.Result;
import com.itsense.lib_sys.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/books")
public class BookController {
    @Autowired
    private BookService bookService;
    //增删改查
    //添加
    @PostMapping
    public Result save(@RequestBody Book book){
        boolean status = bookService.save(book);
        if(status){
            return Result.builder().data(status).msg("保存成功").code(Code.SAVE_OK).build();
        }else{
            return Result.builder().data(status).msg("保存失败").code(Code.SAVE_ERR).build();
        }
    }
    //删除{通过id实现}
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id){
        boolean status = bookService.deleteById(id);
        if(status){
            return Result.builder().data(status).msg("删除成功").code(Code.DELETE_OK).build();
        }else{
            return Result.builder().data(status).msg("删除失败").code(Code.DELETE_ERR).build();
        }
    }
    //修改
    @PutMapping
    public Result update(@RequestBody Book book){
        boolean status = bookService.update(book);
        if(status){
            return Result.builder().data(status).msg("更新成功").code(Code.UPDATE_OK).build();
        }else{
            return Result.builder().data(status).msg("更新失败").code(Code.UPDATE_ERR).build();
        }
    }
    //按照id返回数据
    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id){
        Book book = bookService.getById(id);
        String msg = book == null ? "查找失败" : "查找成功";
        Integer code = book == null ? Code.GET_ERR : Code.GET_OK;
        return new Result(book,msg,code);
    }
    //返回所有数据实现
    @GetMapping
    public Result getAll(){
        List<Book>list = bookService.getAll();
        String msg = list == null ? "查找失败" : "查找成功";
        Integer code = list == null ? Code.GET_ERR : Code.GET_OK;
        return new Result(list,msg,code);
    }
}
